/*
 全局js
 */


/*!
 * jQuery Cookie Plugin v1.4.1
 * https://github.com/carhartl/jquery-cookie
 *
 * Copyright 2006, 2014 Klaus Hartl
 * Released under the MIT license
 */
(function (factory) {
    if (typeof define === 'function' && define.amd) {
        // AMD (Register as an anonymous module)
        define(['jquery'], factory);
    } else if (typeof exports === 'object') {
        // Node/CommonJS
        module.exports = factory(require('jquery'));
    } else {
        // Browser globals
        factory(jQuery);
    }
}(function ($) {

    var pluses = /\+/g;

    function encode(s) {
        return config.raw ? s : encodeURIComponent(s);
    }

    function decode(s) {
        return config.raw ? s : decodeURIComponent(s);
    }

    function stringifyCookieValue(value) {
        return encode(config.json ? JSON.stringify(value) : String(value));
    }

    function parseCookieValue(s) {
        if (s.indexOf('"') === 0) {
            // This is a quoted cookie as according to RFC2068, unescape...
            s = s.slice(1, -1).replace(/\\"/g, '"').replace(/\\\\/g, '\\');
        }

        try {
            // Replace server-side written pluses with spaces.
            // If we can't decode the cookie, ignore it, it's unusable.
            // If we can't parse the cookie, ignore it, it's unusable.
            s = decodeURIComponent(s.replace(pluses, ' '));
            return config.json ? JSON.parse(s) : s;
        } catch(e) {}
    }

    function read(s, converter) {
        var value = config.raw ? s : parseCookieValue(s);
        return $.isFunction(converter) ? converter(value) : value;
    }

    var config = $.cookie = function (key, value, options) {

        // Write

        if (arguments.length > 1 && !$.isFunction(value)) {
            options = $.extend({}, config.defaults, options);

            if (typeof options.expires === 'number') {
                var days = options.expires, t = options.expires = new Date();
                t.setMilliseconds(t.getMilliseconds() + days * 864e+5);
            }

            return (document.cookie = [
                encode(key), '=', stringifyCookieValue(value),
                options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
                options.path    ? '; path=' + options.path : '',
                options.domain  ? '; domain=' + options.domain : '',
                options.secure  ? '; secure' : ''
            ].join(''));
        }

        // Read

        var result = key ? undefined : {},
            // To prevent the for loop in the first place assign an empty array
            // in case there are no cookies at all. Also prevents odd result when
            // calling $.cookie().
            cookies = document.cookie ? document.cookie.split('; ') : [],
            i = 0,
            l = cookies.length;

        for (; i < l; i++) {
            var parts = cookies[i].split('='),
                name = decode(parts.shift()),
                cookie = parts.join('=');

            if (key === name) {
                // If second argument (value) is a function it's a converter...
                result = read(cookie, value);
                break;
            }

            // Prevent storing a cookie that we couldn't decode.
            if (!key && (cookie = read(cookie)) !== undefined) {
                result[name] = cookie;
            }
        }

        return result;
    };

    config.defaults = {};

    $.removeCookie = function (key, options) {
        // Must not alter options, thus extending a fresh object...
        $.cookie(key, '', $.extend({}, options, { expires: -1 }));
        return !$.cookie(key);
    };

}));




(function(){


    var localSave = {

        set:function(key,value){


            if(!key && !value){
                return;
            }

            var val;

            console.log(value)
            if(String(typeof value).toLocaleLowerCase()  == 'object'){
                val = JSON.stringify(value);
            }else{
                val = value;
            }

            if(window.localStorage){
                localStorage.setItem(key,val);
                return;
            }

            if($.cookie){
                $.cookie(key,val, { expires: 30, path: '/' });
            }


        },
        get:function(key){

            var val;

            if(!key){
                return;
            }


            if(window.localStorage){

                val = localStorage.getItem(key) || '';

            }else if($.cookie){

                val = $.cookie(key) || '';
            }


            try {

                val = JSON.parse(val);

            }catch(e){

            }

            return val;
        }
    };

    window.$S = localSave;
})();





function $C(opt) {

    var vdata = opt.data || {};
    vdata.r = new Date().getTime();

    //var aid = new Date().getTime()+'_'+Math.random();
    //if(opt.initTask){
    //    $AjaxList.addAjaxIns(aid);
    //}

    var data = {
        data: vdata,
        url: opt.url || '',
        dataType: opt.dataType || 'json',
        type: opt.type || 'post',
        contentType: "application/x-www-form-urlencoded; charset=utf-8",
        success: function (msg) {

            var v = msg;
            try {
                v = JSON.parse(msg);
            } catch (e) {

            }

            //判断是否未登录

            if(msg && msg.returnCode == 'USER_NOTLOGIN'){


                var redirectURL = window.location.href;


                var isJiangsuProject = window.g_config.isjiangsuProject; //江苏定制
                if(isJiangsuProject){

                    if(window.location.search || ''){
                        redirectURL = redirectURL + '&LinkSource=GuaHaoPlatform'
                    }else{
                        redirectURL = redirectURL + '?LinkSource=GuaHaoPlatform'
                    }

                    redirectURL = encodeURIComponent(redirectURL);
                    redirectURL = 'https://wy.guahao.com/uc/login?ft=8bc4bb22c915aa9c29288e28710ce619&target='+redirectURL;


                }else{

                    redirectURL = encodeURIComponent(redirectURL);
                    redirectURL  = '/User/login?RedirectUrl='+redirectURL;

                }


                window.location.href = redirectURL;

                return;

            }

            if (opt.success) {
                opt.success(v);
            }
        },
        error: function (e) {
            if (opt.error) {
                opt.error(e);
            }//

            if(!navigator.onLine){
                window.$Tip.twinkle('网络已断开')
            }

        },
        complete: function (XMLHttpRequest, status) { //请求完成后最终执行参数

            //$AjaxList.setAjaxInsStatus(aid);
            if (status == 'timeout') {//超时,status还有success,error等值的情况
                _abort();
                $Tip.tip('系统忙，请稍后再试');
                if (opt.timeout) {
                    opt.timeout(status);
                }
            }
        }
    };

    if (opt.async === false) {
        data.async = false;
    }





    if (opt.timeoutset) {
        data.timeout = opt.timeoutset || 10000;
    }

    if (!opt.noMask) {
        //todo Loading
    }
    var ajaxInstance = $.ajax(data);

    function _abort() {
        ajaxInstance.abort();
    }
}



(function () {

    //浏览器地址栏封装


    var queryStringByName = function (name) {

        var result = location.search.match(new RegExp("[\?\&]" + name + "=([^\&]+)", "i"));

        if (result == null || result.length < 1) {

            return "";

        }

        return decodeURIComponent(result[1]);

    };


    function getQueryString(decode) {
        var obj = {};
        var result = location.search.match(new RegExp("[\?\&][^\?\&]+=[^\?\&]+", "g"));
        if (result == null) {
            return obj;

        }


        for (var i = 0; i < result.length; i++) {
            result[i] = result[i].substring(1);
            var temp = result[i].split('=');

            obj[temp[0]] = temp[1];

            if (decode) {
                obj[temp[0]] = decodeURIComponent(temp[1]);
            }
        }
        return obj;
    }


    function getStringSByHash(decode) {
        var obj = {};
        var result = location.hash.match(new RegExp("[\#\&][^\#\&]+=[^\#\&]+", "g"));
        if (result == null) {
            return obj;

        }


        for (var i = 0; i < result.length; i++) {
            result[i] = result[i].substring(1);
            var temp = result[i].split('=');

            obj[temp[0]] = temp[1];

            if (decode) {
                obj[temp[0]] = decodeURIComponent(temp[1]);
            }
        }
        return obj;
    }


    window.$U = {};
    window.$U.getUrlParamByName = queryStringByName;
    window.$U.getUrlParams = getQueryString;
    window.$U.getHashParams = getStringSByHash;
})();








/**
 * 页面列表中见加载
 */
(function () {

    var dialog = {};
    dialog.open = function () {
        var dom = $('#waitLoad')
        if (!dom.length) {

            dom = $('<div class="loader-wrap" id="waitLoad"><div class="loader">  <div class=" ball-clip-rotate">  <div></div> </div> </div></div>');
            $('body').append(dom);
        }
        dom.show();
    };

    dialog.close = function () {
        var dom = $('#waitLoad').hide();
    };


    window.$LS = {
        jamLoad:dialog
    };

})();




/**
 * 页面后置专场
 */
(function () {


    window.onbeforeunload = function () {

        $Load.open();
        console.log('onbeforeunload')


    };
    window.onload = function () {
        $Load.close();
        console.log('onload')
    };

    window.onunload = function () {

        //todo Page Load Animate
        $Load.open();
    }
})();



//util
(function () {

    //日期

    // 对Date的扩展，将 Date 转化为指定格式的String
    // 月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符，
    // 年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字)
    // 例子：
    // (new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423
    // (new Date()).Format("yyyy-M-d h:m:s.S")      ==> 2006-7-2 8:9:4.18

    Date.prototype.Format = function (fmt) { //author: meizz
        var o = {
            "M+": this.getMonth() + 1, //月份
            "d+": this.getDate(), //日
            "h+": this.getHours(), //小时
            "m+": this.getMinutes(), //分
            "s+": this.getSeconds(), //秒
            "q+": Math.floor((this.getMonth() + 3) / 3), //季度
            "S": this.getMilliseconds() //毫秒
        };
        if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
        for (var k in o)
            if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
        return fmt;
    };
    var date = {
        create: function (str) {
            var s = new Date(String(str).replace(/-/g, '/'));
            s = s.getTime() ? new Date(s) : new Date();
            return s;
        },
        minus: function (a, n) {

            var self = this;

            var o = String(typeof a).toLowerCase() == 'string' ? a : self.create(a);
            var g = String(typeof n).toLowerCase() == 'string' ? n : self.create(n);

            var delta = o.getTime() - g.getTime();

            var dayLeft = 0;
            if (delta > 0) {

                dayLeft = delta / (1000 * 3600 * 24);
            } else {
                dayLeft = Math.abs(delta) / (1000 * 3600 * 24);
            }


            return dayLeft;
        },
        /**
         * 日期计算
         * @param date
         * @param delta
         * @param type
         * @return date {Date}
         */
        plus: function (date, delta, type) {


            var self = this;

            var o = self.create(date);
            switch (type) {

                case 'day': o.set(o.getDay() + delta);
                    break;
                case 'month': o.setMonth(o.getMonth() + delta);
                    break;
                case 'year': o.setYear(o.getFullYear() + delta);
                    break;
                default:
            }
            return o;
        }
    };


    //字符串处理

    /**
     * 包含
     * @param o
     * @returns {boolean}
     */
    Array.prototype.contains = function (o) {
        for (var i = 0; i < this.length; i++) {
            if (o === this[i]) {
                return true;
            }
        }
        return false;
    };

    /**
     * 迭代
     * @param fn
     * @returns {Array}
     */
    Array.prototype.each = function (fn) {
        fn = fn || Function.K;
        var a = [];
        var args = Array.prototype.slice.call(arguments, 1);
        for (var i = 0; i < this.length; i++) {
            var res = fn.apply(this, [this[i], i].concat(args));
            if (res != null) a.push(res);
        }
        return a;
    };


    /**
     * 去重
     * @returns {Array}
     */
    Array.prototype.uniquelize = function () {
        var na = [];
        for (var i = 0; i < this.length; i++) {
            if (!na.contains(this[i])) {
                na.push(this[i]);
            }
        }
        return na;
    };

    /**
     * 数组应用方法
     * @param a Array
     * @param b Array
     */
    Array.complement = function (a, b) {
        return Array.minus(Array.union(a, b), Array.intersect(a, b));
    };

    /**
     * 交集
     * @param a
     * @param b
     * @returns {Array}
     */
    Array.intersect = function (a, b) {
        return a.uniquelize().each(function (o) { return b.contains(o) ? o : null });
    };

    /**
     * 差集
     * @param a
     * @param b
     * @returns {Array}
     */
    Array.minus = function (a, b) {
        return a.uniquelize().each(function (o) { return b.contains(o) ? null : o });
    };


    /**
     * 并集
     * @param a
     * @param b
     * @returns {Array}
     */
    Array.union = function (a, b) {
        return a.concat(b).uniquelize();
    };

    window.$Date = date;
})();



/**
 * 调试工具
 * @param info
 * @param level
 */
function devDebug(info, level) {
    var date = new Date().Format('yyyy-MM-d hh:mm:ss');
    var debugStr = '[' + date + ']======>' + info;
    var l = (level || 1) - 1;
    var color = ['grey', 'green', '#efec8d', 'red'];
    if (typeof info == 'object') {
        console.log('%c[' + date + ']======>%o', 'color:' + color[l] + '; background-color:#f3f3f3', info)
    } else {
        console.log('%c' + debugStr, 'color:' + color[l] + '; background-color:#f3f3f3')
    }
}







(function () {

    //本地储存封装
    var localData = {

        get: function (key) {

            if (!key) {
                return null;
            }

            var rs = '';
            var t;
            if (window.localStorage) {

                t = window.localStorage.getItem(key);
                try {

                    t = JSON.parse(t);

                } catch (e) {

                }
                rs = t;

            }

            return rs;
        },
        set: function (key, item) {

            if (!key) {
                return;
            }

            var v = item || '';

            if (v && String(typeof v).toLocaleLowerCase() == 'object') {
                v = JSON.stringify(v);
            }

            if (window.localStorage) {
                window.localStorage.setItem(key, v);
            }

        }
    }


    window.$l = localData;


})();

//URL处理
(function () {



    //转移   todo 安全问题
    function encode(value, opts) {

        var rs = decodeURIComponent(value);

        if (opts.encode) {
            return encodeURIComponent(rs);
        }

        return value;
    }



    function parse(str) {


        var ret = Object.create(null);

        if (typeof str !== 'string') {
            return ret;
        }

        str = str.trim().replace(/^(\?|#|&)/, '');

        if (!str) {
            return ret;
        }

        str.split('&').forEach(function (param) {
            var parts = param.replace(/\+/g, ' ').split('=');
            // Firefox (pre 40) decodes `%3D` to `=`
            // https://github.com/sindresorhus/query-string/pull/37
            var key = parts.shift();
            var val = parts.length > 0 ? parts.join('=') : undefined;

            key = decodeURIComponent(key);

            // missing `=` should be `null`:
            // http://w3.org/TR/2012/WD-url-20120524/#collect-url-parameters
            val = val === undefined ? null : decodeURIComponent(val);

            if (ret[key] === undefined) {
                ret[key] = val;
            } else if (Array.isArray(ret[key])) {
                ret[key].push(val);
            } else {
                ret[key] = [ret[key], val];
            }
        });

        return ret;

    }

    /**
     *
     * jquey.extend实现
     * returns {*|{}}
     */
    function $extend() {

        var options, name, src, copy, copyIsArray, clone,
            target = arguments[0] || {},
            i = 1,
            length = arguments.length,
            deep = false;

        // Handle a deep copy situation
        if (typeof target === "boolean") {
            deep = target;

            // Skip the boolean and the target
            target = arguments[i] || {};
            i++;
        }

        // Handle case when target is a string or something (possible in deep copy)
        if (typeof target !== "object" && !jQuery.isFunction(target)) {
            target = {};
        }

        // Extend jQuery itself if only one argument is passed
        if (i === length) {
            target = this;
            i--;
        }

        for (; i < length; i++) {

            // Only deal with non-null/undefined values
            if ((options = arguments[i]) != null) {

                // Extend the base object
                for (name in options) {
                    src = target[name];
                    copy = options[name];

                    // Prevent never-ending loop
                    if (target === copy) {
                        continue;
                    }

                    // Recurse if we're merging plain objects or arrays
                    if (deep && copy && (jQuery.isPlainObject(copy) ||
                        (copyIsArray = jQuery.isArray(copy)))) {

                        if (copyIsArray) {
                            copyIsArray = false;
                            clone = src && jQuery.isArray(src) ? src : [];

                        } else {
                            clone = src && jQuery.isPlainObject(src) ? src : {};
                        }

                        // Never move original objects, clone them
                        target[name] = jQuery.extend(deep, clone, copy);

                        // Don't bring in undefined values
                    } else if (copy !== undefined) {
                        target[name] = copy;
                    }
                }
            }
        }

        // Return the modified object
        return target;
    }



    function stringify(obj, opts) {


        var defaults = {
            encode: true,
            strict: true
        };

        var opts = $extend(defaults, opts);


        return obj ? Object.keys(obj).sort().map(function (key) {
            var val = obj[key];

            if (val === undefined) {
                return '';
            }

            if (val === null) {
                return encode(key, opts);
            }

            if (Array.isArray(val)) {
                var result = [];

                val.slice().forEach(function (val2) {
                    if (val2 === undefined) {
                        return;
                    }

                    if (val2 === null) {
                        result.push(encode(key, opts));
                    } else {
                        result.push(encode(key, opts) + '=' + encode(val2, opts));
                    }
                });

                return result.join('&');
            }

            return encode(key, opts) + '=' + encode(val, opts);
        }).filter(function (x) {
            return x.length > 0;
        }).join('&') : '';
    }



    window.$URL = {
        parse: parse,
        stringify: stringify
    }

})();


(function () {


    //前置配置

    if (window.juicer) {
        window.juicer.set({
            'tag::operationOpen': '{{',
            'tag::operationClose': '}}'
        });



    }

    window.paramConfig = config;

})();

//发送短信
//实例化

var  smsMsg = function(opt){
    this.configGap = opt.gap || 90;
    this.gap = opt.gap || 90;
    this.url = opt.url  || '/HandleRequest/Member/RegSmsSend';
    this.countSet = '';
    this.countEnd = opt.countEnd || function(){};
    this.tick = opt.tick || function(){};

};

smsMsg.prototype = {

    reset:function(){
        var _self = this;
        _self.gap = _self.configGap;

        clearInterval(_self.countSet);
        if(_self.countEnd){
            _self.countEnd();
        }

    },
    count:function(num){
        var _self = this;
        if(num){
            _self.gap = num;
        }

        clearInterval(_self.countSet); //重置
        _self.countSet = setInterval(function(){
            //_self.trigger('sms.tick',[num]);//before

            if(_self.tick){
                _self.tick(_self.gap);
            }
            if(_self.gap == 0){
                _self.reset();
            }
            _self.gap--;
        },1000);

    },
    send:function(opt){

        var _self = this;

        $C({
            url:_self.url,
            type:'post',
            data:opt.data || _self.data || {},
            success:function(msg){

                if(msg && msg.returnCode == 'SUCCESS'){
                    _self.count(opt.num || '');
                    var suc = opt.suc || _self.suc;
                    if(suc){
                        suc(msg);
                    }
                }else{
                    _self.reset();
                    var fail = opt.fail || _self.fail;
                    if(fail){
                        fail(msg);
                    }

                }
            },
            error:function(e){
                var _self = this;
                //   _self.reset();
                window.$Tip.twinkle('系统忙');
            }
        });

    }
};